package com.lxl.commons.contants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 北上寻海
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取method参数，是前端发送请求时带过来的，相当于标识
        String methodName = request.getParameter("method");
        if(methodName==null||methodName.trim().isEmpty()){
            throw new RuntimeException("请输入method参数");
        }
        //获取继承BaseServlet的子类的字节码对象
        Class clazz = this.getClass();
        //通过clazz字节码对象获取对应的方法的对象
        Method method =null;
        try {
            //参数第一个是方法名，后面的是方法对应参数的class
            method = clazz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("您传入的"+methodName+"不存在");
        }
        try {
            method.invoke(this,request,response);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            System.out.println("BaseServlet程序内部错误");
            throw new RuntimeException(e);
        }
    }
}
